package com.mach.platform.api.service;

import com.mach.platform.api.domain.Bill;
import com.mach.platform.api.domain.BillDetails;
import com.mach.platform.api.repository.BillDetailsRepo;
import com.mach.platform.api.repository.BillRepo;
import com.mach.platform.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 账单业务类
 */

@Slf4j
@Service
public class BillServiceImpl implements BaseService<Bill> {

    @Autowired
    private BillRepo billRepo;

    @Autowired
    private BillDetailsRepo billDetailsRepo;

    @Override
    public Bill save(Bill bill) {
        if (bill != null){
            bill.setPayState(1);
            bill.setInvoiceState(1);
            // 保存账单
            Bill result = billRepo.save(bill);
            if (bill.getBillDetails() != null){
                bill.getBillDetails().forEach(item -> item.setBillId(bill.getId()));
                // 保存账单明细
                billDetailsRepo.saveAll(bill.getBillDetails());
            }
            return result;
        }
        return null;
    }

    @Override
    public List<Bill> insertObjInBatch(List<Bill> list) {
        return null;
    }

    @Override
    public Bill update(Bill bill) {
        if (bill != null) {
            this.save(bill);
        }
        return null;
    }

    @Transactional
    @Override
    public int delete(Long[] ids) {
        if (ids != null && ids.length > 0){
            int result = billRepo.deleteByIdIn(ids);
            billDetailsRepo.deleteByBillId(ids);
            return result;
        }
        return 0;
    }

    @Override
    public Page<Bill> list(Pageable pageable, Map params) {
        return null;
    }

    @Override
    public Bill info(Long id) {
        if (id != null){
            Bill bill = billRepo.getById(id);
            if (bill != null){
                ArrayList<BillDetails> billDetails = billDetailsRepo.getListByBillId(bill.getId());
                // 计算总金额
                double total = count(billDetails);
                bill.setTotalMoney(total);
                bill.setBillDetails(billDetails);
                return bill;
            }
        }
        return null;
    }

    private double count(List<BillDetails> billDetails) {
        double total = 0.0;
        if (billDetails != null && billDetails.size() > 0) {
            for (BillDetails billDetails1 : billDetails){
                if (billDetails1.getTotal() != null){
                    total += billDetails1.getTotal();
                }
            }
        }
        return total;
    }
}
